#include "songmenu.h"

#include <QtGui>
#include "ktv/ktv.h"
#include "ktv/model/resource/resource.h"

SongMenu::SongMenu(KTV *k, int w, int h)
    : GUI(k),
    ktv(k), width(w), height(h)
{
    setFlag(QGraphicsItem::ItemIsFocusable);

    resource = Resource::getInstance();
    backgroundPixmap = 0;

    appearance = resource->songmenu_appearance;
    option = resource->songmenu_option;

    currMenu = 0;
    index_for_animation = 0;
    animation = new QPropertyAnimation(this, "index");
    animation->setEasingCurve(QEasingCurve::InOutSine);
    connect(animation, SIGNAL(finished()), this, SLOT(animationFinish()));

    backgroundPixmap = option->first();
}

void SongMenu::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_M:
        ktv->hideSongMenu();
        break;
    case Qt::Key_Q:
        ktv->hideSongMenu();
        break;
    case Qt::Key_Right:
        nextMenu();
        break;
    case Qt::Key_Left:
        previousMenu();
        break;
    case Qt::Key_Y:
        ktv->selectSongMenu(currMenu);
        break;
    }
}

void SongMenu::select()
{
    ktv->selectSongMenu(currMenu);
}

void SongMenu::appear()
{
    currMenu = 0;
    index_for_animation = 0;
    backgroundPixmap = option->first();
    startAnimation();
}

void SongMenu::disappear()
{
    animation->setStartValue(appearance->size() - 1);
    animation->setEndValue(0);
    animation->start();
//    connect(animation, SIGNAL(finished()), this, SLOT(afterDisappear()));
}

void SongMenu::afterDisappear()
{
//    setVisible(false);
}

void SongMenu::nextMenu()
{
    if (animation->state() == QAbstractAnimation::Running) {
        return;
    }
    currMenu++;
    currMenu %= option->size();
    backgroundPixmap = option->at(currMenu);
    update();
}

void SongMenu::previousMenu()
{
    if (animation->state() == QAbstractAnimation::Running) {
        return;
    }
    currMenu--;
    if (currMenu < 0) {
        currMenu += 2;
    }
    backgroundPixmap = option->at(currMenu);
    update();
}

void SongMenu::startAnimation()
{
    qDebug() << "song menu is busy.";
    ktv->setGuiUsable(false);

    animation->setStartValue(0);
    animation->setEndValue(appearance->size()-1);
    animation->start();
}

void SongMenu::setIndexForAnimation(int index)
{
    index_for_animation = index;
    backgroundPixmap = appearance->at(index);
    update();
}

QRectF SongMenu::boundingRect() const
{
    return QRectF(-width/2.0, -height/2.0, width, height);
}

void SongMenu::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(painter);
    Q_UNUSED(option);
    painter->drawPixmap(-width/2.0, -height/2.0, width, height, *backgroundPixmap);
}
